package com.cw.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Encrypt {
	private static char[] buf = new char[256];
	static int BUFSIZE = 256;
	static int OFFSET = 16;
	static int ROTATE = 7;

	static int SEED = 5;

	public static String decrypt(int lno, String str) {
		int seed = lno + SEED;
		int rotate = seed % ROTATE;
		int offset;
		for (int ii = 0; ii < BUFSIZE; ii++) {
			buf[ii] = '\0';
		}
		int strlen = str.length();
		for (int ii = 0; ii < strlen; ii++) {
			offset = (seed + ii * ii) % OFFSET;
			buf[ii] = (char) (str.charAt(ii) + offset);
		}
		String enpstr = new String(buf);
		return enpstr.substring(strlen - rotate, strlen)
				+ enpstr.substring(0, strlen - rotate);
	}

	public static String decrypt(String str) {
		return decrypt(SEED, str);
	}

	public static String decryptComma(String plain) {
		StringBuffer hexbuf = new StringBuffer();

		for (int ii = 0; ii < plain.length(); ii += 2) {
			hexbuf.append((char) Integer.parseInt(plain.substring(ii, ii + 2),
					16));
		}

		return decrypt(hexbuf.toString());
	}

	public static String encrypt(int lno, String str) {
		int seed = lno + SEED;
		int rotate = seed % ROTATE;
		int offset;
		for (int ii = 0; ii < BUFSIZE; ii++) {
			buf[ii] = '\0';
		}
		String rstr = str.substring(rotate) + str.substring(0, rotate);
		for (int ii = 0; ii < str.length(); ii++) {
			offset = (seed + ii * ii) % OFFSET;
			buf[ii] = (char) (rstr.charAt(ii) - offset);
		}
		return (new String(buf)).substring(0, str.length());
	}

	public static String encrypt(String str) {
		return encrypt(SEED, str);
	}

	public static String encryptComma(String plain) {
		StringBuffer hexbuf = new StringBuffer();

		String val = encrypt(plain);

		for (int ii = 0; ii < plain.length(); ii++) {
			hexbuf.append(Integer.toHexString((int) val.charAt(ii)));
		}

		return hexbuf.toString();
	}

	public static void main(String args[]) throws IOException {

		System.out.println("input a String:");
		FileReader reader = new FileReader(SystemProperties.USER_DIR
				+ "/resource/doubleball.xml");

		BufferedReader in = new BufferedReader(reader);
		String enStr = encrypt(in.toString());
		String deStr = decrypt(enStr);

		String inputLine = in.readLine();
		String enLine = encrypt(inputLine);
		String deLine = decrypt(enLine);
		System.out.println("the encrypt is:" + enLine);
		System.out.println("the decrypt is:" + deLine);

		System.out.println("the encrypt is:" + enStr);
		System.out.println("the decrypt is:" + deStr);

	}
}
